
#include "flame.h"
#include "army.h"
#include "resourcemanager.h"
#include "gamemanager.h"
#include "frameanimation.h"
#include "CCSkeletalSprite.h"
#include "gamedatamanager.h"
#include "gamescene.h"

static const float FLAME_DELAY = 0.1f;

#define __super         Bullet

FlameBullet::FlameBullet(Unit* target,
		EquipmentAttribute *attr):
__super(attr)
, _targetFaction(ArmyFaction::left)
, _timeElapsed(0.0f)
, _bulletNumber(0)
, _targetArmy(nullptr)
{
	dst = target->position;
	_targetFaction = target->faction;
	_targetLineIndex = target->gridInfo.globalLineIndex;
	_targetRowIndex = target->gridInfo.rowIndex;
	_targetArmy = target->ourArmy;

}

FlameBullet::~FlameBullet() {
}

void FlameBullet::init() {

}

bool FlameBullet::update(float ticks) {
	bool ret = false;

	if(_bulletNumber < bulletAttribute->splashCases) {
		ret = true;

		_timeElapsed += ticks;
		if(_timeElapsed >= FLAME_DELAY) {
			FrameAnimation *fxHit = RM->createAnimation("fx_fire_hit", dst);
			fxHit->setLoop(false);
			fxHit->setAnchorPoint(ccp(0.5f, 0.0f));
			fxHit->setZOrder(static_cast<int>(GM->screenSize.height - dst.y));

			ManagedGameNodeInfo _managedGameNodeInfo;
			_managedGameNodeInfo.node = fxHit;
			GM->gameScene->addOneTimeNode(_managedGameNodeInfo);

			int lineIndex = _targetLineIndex + _bulletNumber;
			if(lineIndex < TOTAL_LINES) {
				Unit* unit = _targetArmy->getSoldier(lineIndex, _targetRowIndex);
				if(unit && unit->isAlive()) {
					float distance = dst.getDistance(unit->position);
					if(distance <= GRID_WIDTH / 2.0f) {
						unit->applyBullet(this);
					}
				}
			}

			_timeElapsed = 0.0f;
			_bulletNumber++;

			if(_targetFaction == ArmyFaction::left) {
				dst.x -= GRID_WIDTH;
			} else {
				dst.x += GRID_WIDTH;
			}
		}
	}

	return ret;
}
